import 'package:flutter/material.dart';
import 'package:permission_handler/permission_handler.dart';
//import 'package:taudio/public/fs/flutter_sound_recorder.dart';

import '../manager/AudioStreamManager.dart';
import '../utils/tips.dart';

class AudioRecorderScreen extends StatefulWidget {
  @override
  _AudioRecorderScreenState createState() => _AudioRecorderScreenState();
}

class _AudioRecorderScreenState extends State<AudioRecorderScreen> {
  final audioManager = AudioStreamManager();
  bool isRecording = false;
  int _recordedBytes = 0;

  @override
  void initState() {
    super.initState();

    /*audioManager.startService().then((v) {
      // 检查当前录音状态
      audioManager.isRecording().then((value) {
        setState(() {
          isRecording = value;
        });
      });
    });*/
    // audioManager.initService();


  }

  @override
  void dispose() {
    if (isRecording) {
      audioManager.stopRecording();
    }
    super.dispose();
  }

  /*void _toggleRecording() async {
    var status = await Permission.microphone.request();
    if (status != PermissionStatus.granted) {
      Tips.showToast('Microphone permission not granted');
      throw RecordingPermissionException('Microphone permission not granted');

    }

    var storageStatus = await Permission.storage.request();
    if (storageStatus != PermissionStatus.granted) {
      var storageStatus2 = await Permission.manageExternalStorage.request();
      if (storageStatus2 != PermissionStatus.granted) {
        Tips.showToast('Storage permission not granted');
        throw RecordingPermissionException('Storage permission not granted');
      }
    }


    if (isRecording) {
      await audioManager.stopRecording();
    } else {
      await audioManager.startRecording();
      // 监听音频流
      audioManager.audioStream.listen((data) {
        setState(() {
          _recordedBytes += data.length;

        });
      }, onError: (error) {
        print("Error receiving audio stream: $error");
      });
    }

    setState(() {
      isRecording = !isRecording;
    });
  }*/

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('音频录音示例')),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(isRecording ? '录音中...' : '点击开始录音'),
            SizedBox(height: 20),
            Text('已接收字节: $_recordedBytes'),
            SizedBox(height: 20),
            /*ElevatedButton(
              onPressed: _toggleRecording,
              child: Text(isRecording ? '停止录音' : '开始录音'),
            ),*/
          ],
        ),
      ),
    );
  }
}